package projects.jnurse.ioc.core;

import java.util.*;

/**
 * Created by Adil Naji.
 * User: XP-170708
 * Date: 15 nov. 2008
 * Time: 16:40:00
 */
public class DependencyStore implements Iterable {

    public static DependencyStore instance = new DependencyStore();

    List<Entry> store = new ArrayList<Entry>();

    public Object resolve(String alias) {

        int position = Collections.binarySearch(
                store, EntryExample.getExample(alias));
        if (position >= 0) {
            return store.get(position);
        }

        return null;
    }

    public void addDependency(String alias, Object ref) {
        //store.put(alias, ref);
        store.add(new Entry(alias, ref));
        Collections.sort(store);
    }

    /**
     * FIXME: equals, compareTo, et hashCode comptent sur le seul alias
     */
    public static class Entry implements Comparable<Entry> {
        String alias;
        Object ref;

        public Entry(String alias, Object ref) {
            this.alias = alias;
            this.ref = ref;
        }
        public Entry() { }

        public int compareTo(Entry that) {
            return alias.compareTo(that.alias);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj instanceof Entry) {
                Entry that = (Entry) obj;
                return alias.equals(that.alias);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return alias.hashCode();
        }
    }

    public static class EntryExample {
        static Entry entry = new Entry();

        synchronized static public Entry getExample(String alias) {
            entry.alias = alias;
            return entry;
        }
    }

    public Iterator<Entry> iterator() {
        return new Iterator<Entry>() {
            //Set<Map.Entry<String, Object>> entries = store.entrySet();
            Iterator<Entry> iterator = store.iterator();
            public boolean hasNext() {
                return iterator.hasNext();  //To change body of implemented methods use File | Settings | File Templates.
            }

            public Entry next() {
                return iterator.next();  //To change body of implemented methods use File | Settings | File Templates.
            }

            public void remove() {
                iterator.remove();
            }
        };
    }
}
